#include "list.h"

List Create ( char *filename )
{
	List list = malloc ( sizeof(struct list) );
	list->pollResults.yes = 0;
	list->pollResults.no = 0;
	sprintf ( list->filename, "%s.votes", filename );
	list->size = 0;

	FILE *file = fopen ( list->filename, "r+" );
	
	/* If the poll log files does not exist, create it */

	if (file == NULL) 
	{
		file = fopen ( list->filename, "w" );
		fclose ( file );
		return list;
	}

	/* Load the poll data in the list */

	int i, size;
	fscanf ( file, "%d", &size );

	for ( i = 0; i < size; i++ )
	{
		char username[125];
		int vote;

		fscanf ( file, "%s %d", username, &vote );

		if ( vote == 1 )
		{
			Insert ( list, username, TRUE );	
		}
		else if ( vote == 0 )
		{
			Insert ( list, username, FALSE );	
		}
	}

	fclose ( file );

	return list;
}

BOOL Insert ( List list, char *username, BOOL vote )
{
	if ( list == NULL )
	{
		return FALSE;
	}	

	Node temp;
	Node new = malloc ( sizeof( struct node ) );

	if ( new == NULL )
	{
		return FALSE;
	}

	strcpy ( new->data.username, username );
	new->data.vote = vote;
	temp = list->start;
	list->start = new;
	new->next = temp;

	list->size++;

	/* Update poll results */

	if ( vote == TRUE )
	{
		list->pollResults.yes++;
	}
	else
	{
		list->pollResults.no++;
	}

	return TRUE;	
}

BOOL Exists ( List list, char *username )
{
	if ( list == NULL )
	{
		return FALSE;
	}

	Node temp = list->start;

	int i;
	for ( i = 0; i < list->size; i++ )
	{
		if ( strcmp (temp->data.username, username) == 0 )
		{
			return TRUE;
		}
		temp = temp->next;
	}

	return FALSE;
}

/* Write the data back to disc */

void Flush ( List list )
{
	if ( list == NULL )
	{
		return;
	}

	FILE *file = fopen( list->filename, "w" );
	Node temp = list->start;

	fprintf ( file, "%d\n", list->size );

	int i;
	for ( i = 0; i < list->size; i++ )
	{
		fprintf ( file, "%s %d\n", temp->data.username, temp->data.vote );
		temp = temp->next;
	}	

	fclose ( file );
}

PollResults GetPollResults ( List list, PollResults *pollResults )
{
	pollResults->yes = list->pollResults.yes;
	pollResults->no = list->pollResults.no;
}

































